import React, { useEffect, useState } from 'react';

import { Toast, NavBar } from 'react-vant';

interface VideoItem {
  id:number, 
  title: string;
  src: string;
  playCount: number;
}


function Video() {
  const [videoList, setVideoList] = useState<VideoItem[]>([]);

  // 从json-server获取数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('http://localhost:3001/videoList');
        if (!response.ok) {
          throw new Error('网络响应不正常');
        }
        const data = await response.json();
        setVideoList(data);
      } catch (error) {
        console.error('获取视频数据失败:', error);
      }
    };
    fetchData();
  }, []);

  // 处理视频播放结束事件
  const handlePlayEnd = async (index: number) => {
    try {
      const updatedVideo = {
        ...videoList[index],
        playCount: videoList[index].playCount + 1
      };
  
      // 使用视频的 id 而不是索引
      await fetch(`http://localhost:3001/videoList/${videoList[index].id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updatedVideo),
      });
  
      // 更新本地状态
      setVideoList(prevList => {
        const newList = [...prevList];
        newList[index] = updatedVideo;
        return newList;
      });
    } catch (error) {
      console.error('更新播放次数失败:', error);
    }
  };



    return <div>
{/* 顶部导航栏 */}
       <NavBar
      title="视频"
      onClickLeft={() => 
        //返回shouye
        window.location.href='/'
      }
    />



<ul>
        {videoList.length > 0 ? videoList.map((item, index) => (
          <li key={index} style={{width: "100%", padding:"0 15px", fontSize:'16px',margin:"15px 0"}}>
            <p style={{marginBottom:'5px'}}>{item.title}</p>
            <div>
              <video 
                controls 
                width="100%" 
                src={item.src} 
                style={{width:"100%",height:"200px"}}
                onEnded={() => handlePlayEnd(index)}
              >
                您的浏览器不支持视频标签。
              </video>
            </div>
            <p style={{fontSize: '12px', color: '#666',marginTop:'5px'}}>播放次数：{item.playCount}</p>
          </li>
        )) : <p>加载中...</p>}
      </ul>
    </div>;
  }

  export default  Video


